package com.marry.multidatasource.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author ml
 * @create 2018-01-04--15:37
 */
@Configuration
@MapperScan(basePackages = "com.marry.multidatasource.mapper.fg",sqlSessionTemplateRef = "fgSqlSessionTemplate")
public class FGDataSourceConfig {

    @Bean(name = "fgDataSource",initMethod = "init",destroyMethod = "close")
    @ConfigurationProperties(prefix = "spring.datasource.druid.fg")
    public DruidDataSource fgDataSource(){
        return new DruidDataSource();
    }


    @Bean(name = "fgSqlSessionFactory")
    public SqlSessionFactory fgSqlSessionFactory(@Qualifier("fgDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factoryBean=new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/fg/*.xml"));
        factoryBean.setTypeAliasesPackage("com.marry.multidatasource.model.fg");
        return factoryBean.getObject();
    }

    @Bean(name = "fgTransactionManager")
    public DataSourceTransactionManager fgTransactionManager(@Qualifier("fgDataSource") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "fgSqlSessionTemplate")
    public SqlSessionTemplate fgSqlSessionTemplate(@Qualifier("fgSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
